package com.pdd.kafka.config;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.stereotype.Component;
import org.springframework.util.concurrent.ListenableFuture;
import org.springframework.util.concurrent.ListenableFutureCallback;

/**
 * @author:liyangpeng
 * @date:2020/4/21 15:31
 */
@Slf4j
@Component
public class KafkaProducer {

    @Autowired
    private KafkaTemplate<String,Object> kafkaTemplate;

    public static final String TOPIC_TEST="pdd";

    public static final String TOPIC_GROUP1="topic.group1";

    public static final String TOPIC_GROUP2="topic.group2";

    /**
     * 消息发送
     * @param object
     */
    public void send(Object object){
        ListenableFuture<SendResult<String, Object>> send = kafkaTemplate.send(TOPIC_TEST, object);
        send.addCallback(new ListenableFutureCallback<SendResult<String, Object>>(){
            @Override
            public void onFailure(Throwable throwable) {
                log.error("[kafka-消息发送]发送失败:{}",throwable);
            }

            @Override
            public void onSuccess(SendResult<String, Object> stringObjectSendResult) {
                log.info("[kafka-消息发送]发送成功:{}",stringObjectSendResult.toString());
            }
        });
    }
}
